package edu.udel.gemini.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;

public class Parser {
	
	/* Parses a file with assembly code into a list of Instructions */
	public static List<Instruction> getInstructionsFromFile(MultipartFile multipartFile) throws IOException
	{
		List<Instruction> instructions = new ArrayList<Instruction>();
		InputStream inputStream = multipartFile.getInputStream();
		  BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
		    			
		  String line;
		  int i = 0;
		  while ((line = bufferedReader.readLine()) != null)
		  {
			  instructions.add(getInstructionFromLine(line, i));   
			  i++;
		  }
		  return instructions;
	}
	
	/* Parses a string into a Instruction */
	public static Instruction getInstructionFromLine(String line, int lineNum)
	{
		Instruction instruction = new Instruction();
		instruction.setLine(lineNum);
		String[] s = line.split("\\s+");
		for (String i: s) {
			if (!StringUtils.isBlank(i) && instruction.getOperation() != null) {
				instruction.setRegister(i);
				break;
			}
			if (!StringUtils.isBlank(i) && instruction.getOperation() == null) {
				instruction.setOperation(i);
			}	
		}

		return instruction;
	}

}
